import { NextRequest, NextResponse } from 'next/server';
import { getDeviceParameterDb } from '@/lib/device-parameter-database';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const deviceIdStr = searchParams.get('deviceId');
    const parameterType = searchParams.get('type'); // 'naming', 'position', 'base'

    if (!deviceIdStr || !parameterType) {
      return NextResponse.json({ error: 'deviceId 和 type 参数是必需的' }, { status: 400 });
    }

    // 确保deviceId是数字
    const deviceId = parseInt(deviceIdStr);
    if (isNaN(deviceId)) {
      return NextResponse.json({ error: '无效的设备ID格式' }, { status: 400 });
    }

    const db = getDeviceParameterDb();
    const deviceData = db.getDeviceWithParameters(deviceId);

    if (!deviceData || !deviceData.mapping) {
      return NextResponse.json([]);
    }

    // 转换参数类型名称
    let type: string;
    switch (parameterType) {
      case 'naming':
        type = 'naming';
        break;
      case 'position':
        type = 'position';
        break;
      case 'base':
        type = 'base_params';
        break;
      default:
        return NextResponse.json({ error: '无效的参数类型' }, { status: 400 });
    }

    // 获取参数数据和字段定义
    const parameters = deviceData.parameters[type as keyof typeof deviceData.parameters] || {};
    const tableName = deviceData.mapping[`${type}_table` as keyof typeof deviceData.mapping] as string;
    const fieldMetadata = tableName ? db.getParameterTableFields(tableName) : [];

    // 转换为旧API格式
    const result = fieldMetadata.map((field, index) => ({
      id: index + 1,
      parameter_name: field.field_name,
      parameter_value: parameters[field.field_name] || '',
      data_type: field.data_type,
      is_required: field.is_required,
      sequence: field.field_sequence.toString(),
      example_description: field.example_description,
      measurement_class: field.measurement_class,
      data_source: field.data_source
    }));

    return NextResponse.json(result);
  } catch (error: any) {
    // 明确返回JSON格式错误信息
    console.error('获取参数失败:', error);
    return NextResponse.json({ error: error?.message || String(error) || '获取参数失败' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const data = await request.json();
    const { deviceId, parameters } = data;

    if (!deviceId || !parameters || !Array.isArray(parameters)) {
      return NextResponse.json({
        success: false,
        error: '缺少必要参数'
      }, { status: 400 });
    }

    const db = getDeviceParameterDb();
    const deviceData = db.getDeviceWithParameters(deviceId);

    if (!deviceData || !deviceData.mapping) {
      return NextResponse.json({
        success: false,
        error: '设备不存在或没有参数映射'
      }, { status: 404 });
    }

    // 按参数类型分组
    const paramsByType: Record<string, Record<string, any>> = {
      naming: {},
      position: {},
      base_params: {}
    };

    for (const param of parameters) {
      const parameterName = param.parameter_name;
      const parameterValue = param.parameter_value || '';

      // 根据参数名称确定类型（这里需要根据实际的字段映射来判断）
      let type = 'base_params'; // 默认为基础参数

      // 简单的类型判断逻辑，可以根据实际需要调整
      if (parameterName.includes('编码') || parameterName.includes('名称') || parameterName.includes('标识')) {
        type = 'naming';
      } else if (parameterName.includes('位置') || parameterName.includes('地址') || parameterName.includes('坐标')) {
        type = 'position';
      }

      paramsByType[type][parameterName] = parameterValue;
    }

    // 保存各类型的参数
    for (const [type, typeParams] of Object.entries(paramsByType)) {
      if (Object.keys(typeParams).length > 0) {
        try {
          await fetch('/api/device-parameters', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              deviceId,
              type,
              data: typeParams
            })
          });
        } catch (error) {
          console.error(`保存${type}参数失败:`, error);
        }
      }
    }

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('参数保存失败:', error);
    return NextResponse.json({
      success: false,
      error: error?.message || String(error) || '保存参数失败'
    }, { status: 500 });
  }
}

export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { deviceId: deviceIdInput, parameterType, parameterId, parameterValue } = body;

    if (!deviceIdInput || !parameterType || !parameterId) {
      return NextResponse.json({ error: '缺少必需的参数' }, { status: 400 });
    }

    const deviceId = typeof deviceIdInput === 'string' ? parseInt(deviceIdInput) : deviceIdInput;
    if (isNaN(deviceId)) {
      return NextResponse.json({ error: '无效的设备ID格式' }, { status: 400 });
    }

    // 转换参数类型
    let type: string;
    switch (parameterType) {
      case 'naming':
        type = 'naming';
        break;
      case 'position':
        type = 'position';
        break;
      case 'base':
        type = 'base_params';
        break;
      default:
        return NextResponse.json({ error: '无效的参数类型' }, { status: 400 });
    }

    // 这里需要根据parameterId获取参数名称，然后更新
    // 由于旧API使用的是数字ID，而新系统使用字段名，需要做映射
    const db = getDeviceParameterDb();
    const deviceData = db.getDeviceWithParameters(deviceId);

    if (!deviceData || !deviceData.mapping) {
      return NextResponse.json({ error: '设备不存在或没有参数映射' }, { status: 404 });
    }

    const tableName = deviceData.mapping[`${type}_table` as keyof typeof deviceData.mapping] as string;
    const fields = tableName ? db.getParameterTableFields(tableName) : [];

    // 根据parameterId找到对应的字段名
    const fieldIndex = parseInt(parameterId) - 1;
    if (fieldIndex < 0 || fieldIndex >= fields.length) {
      return NextResponse.json({ error: '无效的参数ID' }, { status: 400 });
    }

    const fieldName = fields[fieldIndex].name;

    // 更新参数
    const updateData = { [fieldName]: parameterValue };

    try {
      const response = await fetch('/api/device-parameters', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          deviceId,
          type,
          data: updateData
        })
      });

      if (response.ok) {
        return NextResponse.json({ success: true });
      } else {
        return NextResponse.json({ error: '参数更新失败' }, { status: 500 });
      }
    } catch (error: any) {
      console.error('参数更新失败:', error);
      return NextResponse.json({ error: error?.message || String(error) || '参数更新失败' }, { status: 500 });
    }
  } catch (error: any) {
    console.error('更新参数失败:', error);
    return NextResponse.json({ error: error?.message || String(error) || '更新参数失败' }, { status: 500 });
  }
} 